<?php
namespace  api\modules\v1\controllers;

/**
 * 合约活动
 * 2020/08/07
 * gonglei
 */

use common\bonus\BaseBonus;
use common\models\Balance;
use common\models\BalanceType;
use common\models\GroupDetail;
use common\models\StaticInstance;
use common\models\TradeCommodity;
use common\models\TradeModel;
use common\models\TradeOrder;


class  CommodityController extends CoreController {


    /*投资列表*/
    public function actionList(){

        $whereArr = array();
        $pt     = $this->request['pt'];
        /*销售开始时间小于当前&&结束时间大于当前*/
        $whereArr['where'] = 'sell_end_time >="'.date('Y-m-d',time())
            .'" and sell_start_time<="'.date('Y-m-d',time()).'"';
        if ($pt==1){
            $whereArr['where'].=' and type=3';
        }else {
            $whereArr['where'].=' and type<>3';
        }
        $params = array(
            'field' => ['*'],
            'order' => 'commodity_id DESC',
            'memberId'=>$this->_memberId,
        );

        $data = TradeCommodity::dataList($whereArr,$params,['group']);
        $category = TradeCommodity::find()->select('commodity_category as id')->distinct()->asarray()->all();
//        $tmpData = array_column($category, 'commodity_category');
//        $tmpData = array_values($category);

        $result = array();
        for($i=0;$i<count($category);$i++){
            $tmpArr = array();
            $tmpArr['id'] = $category[$i]['id'];
            $name = '影视合约';
            if(''.$category['id']=='1'){
                $name = '影视合约';
            }else if(''.$category['id']=='2'){
                $name = '破产清算合约';
            }else if(''.$category['id']=='3'){
                $name = '智能狗合约';
            }else if(''.$category['id']=='4'){
                $name = '光量子科技合约';
            }else if(''.$category['id']=='5'){
                $name = '5G合约';
            }else if(''.$category['id']=='6'){
                $name = '代充值合约';
            }
            $tmpArr['name'] = $name;
            $result[] = $tmpArr;
        }
        $this->out('投资列表',$data, ['category'=>$result]);
    }



    /*参加签约*/
    public function actionSetCommodity(){
        $arr['member_id']    = $this->_memberId;
        $arr['goods_id']     = $this->request('commodity_id');
        $arr['amount']       = $this->request('money');

        if(!$this->_member['state']) $this->error('你暂不能此操作');
        
        if (!$arr['goods_id'])
            $this->error('请选择投资项目');

        if ($this->_member['paypwd'] !== md5($this->request('password')))
            $this->error('密码有误');

        if (!$arr['amount'])
            $this->error('配置错误');



        $where = 'commodity_id='.$arr['goods_id'].' and sell_end_time >="'.date('Y-m-d',time())
            .'" and sell_start_time<="'.date('Y-m-d',time()).'"';

        $data  = TradeCommodity::getOne($where);
        if (!$data) $this->error('项目不存在');

        if ($arr['amount']>$data['money_up'] || $arr['amount']<$data['money_down'])
            $this->error('金额必须在'.$data['money_up'].'-'.$data['money_down']);

        $userBalance = Balance::getOne('member_id='.$arr['member_id'].' and balance_type=2','balance');

        if (!$userBalance)  $this->error('用户余额为空');
        //根据UPH行情，算出当前合约需要的UPH数量
        $fromPrice = BalanceType::getOne(['type' => 1], ['price'])['price'];
        $toPrice = BalanceType::getOne(['type' => 2], ['price'])['price'];
        $toTotal = round($arr['amount'] * $fromPrice / $toPrice, 2);
        if ($userBalance['balance']<$toTotal) $this->error('用户余额不足');
        $arr['type']  = $data['type'];
        $arr['period']=$data['period'];
        $tradeOrder = new TradeOrder();
        try {

            //创建订单
            $transaction = \Yii::$app->db->beginTransaction();
            $orderId     =  $tradeOrder->addData($arr,$this->_member);
            if(!$orderId) throw new \Exception("订单创建失败");

            //扣除余额账本
            $res = Balance::reduceBalance($arr['member_id'],2,$toTotal,5,$orderId);
            if (isset($res['state']) && $res['state']==false) throw new \Exception($res['msg']);

            //增加合同钱包
            $re = Balance::addBalance($arr['member_id'],3,$arr['amount'],5,$orderId);
            if (isset($re['state']) && $re['state']==false) throw new \Exception($re['msg']);
            $transaction->commit();

            //触发后续
            $params              = array();
            $params['money']     = $arr['amount'];
            $params['member_id'] = $this->_memberId;
            $params['source_id'] = 1;
            $params['mch_id']    = 0;
            $params['trigger_type'] = 1;
            $params['desc']         = 'from 【'.$this->_member['member_name'].'】';
            $params['order_type']   = $data['type'];
            $params['period']       = $data['period']??0;
            $params['day_income']   = $data['day_income'];
            $params['commodity_id'] = $arr['goods_id'];
            $params['zhitui_income'] = $data['zhitui_income'];
            BaseBonus::bonusRun($params);
            $this->out('签约成功');
        }catch (\Exception $e){
           $transaction->rollback();
            $this->error($e->getMessage());
        }
    }


    /*我的合同列表*/
    public function actionCommodityList(){
        $whereArr = $this->formartWhere();

        if (empty($whereArr['where']['type']))  $whereArr['where']['type']=1;


        $params = array(
            'field'	=> ['id','in_num','type','status','bonus_day','period_day','order_type','create_time','commodity_id'],
            'order' => 'create_time desc',
            'page'	=> $this->request('page',1),
            'limit' => $this->request('page_size',10),
            'member_id'=>$this->_memberId,
        );

        $data  = StaticInstance::dataList($whereArr,$params,['winning']);
        $count = StaticInstance::$pages;
        $this->out('合约列表',$data,['count'=>$count]);
    }


    /*我的合同统计信息*/
    public function actionCommodityInfo(){
        /*有效收益*/
        $wherep = ['member_id'=>$this->_memberId,'status'=>1,'order_type'=>[2,3]];
        $data['profit']  = StaticInstance::find()->where($wherep)->count('id');

        /*过期的*/
        $whereo = ['member_id'=>$this->_memberId,'status'=>2,'order_type'=>[2,3]];
        $data['overdue']  = StaticInstance::find()->where($whereo)->count('id');

        /*自由理财*/
        $wheref = ['member_id'=>$this->_memberId,'status'=>1,'order_type'=>'1'];
        $data['freedom']  = StaticInstance::find()->where($wheref)->count('id');

        /*全部*/
        unset($wherep['status']);
        $wherep['order_type']=[1,2,3];
        $data['count']   = StaticInstance::find()->where($wherep)->count('id');
        $this->out('我的合同统计',$data);
    }

        /*
    *列表 条件组装
    */
    public function formartWhere()
    {
        $where = [];
        $whereAnd = [];
        if (!$this->request('search')){
            return [];
        }
        $searchKeys = json_decode($this->request('search'),1);
        foreach($searchKeys as $k=>$val)
        {
            if($val=='') continue;
            if($k=='date')
            {
                if(!$val['0'] || !$val['1']) continue;
                $whereAnd[] = ['between', 'create_time', strtotime($val[0]),strtotime($val[1])];
            }else
            {
                $where[$k] = $val;
            }
        }
        return array('where'=>$where,'whereAnd'=>$whereAnd);
    }


    /*解约 提取本金 二期需要将USDT转为UPH*/
    public function actionRelieve(){
        $id = $this->request['id'];
        if (!$id) $this->error('请选择合约');
        $instance = StaticInstance::getOne(['id'=>$id,'member_id'=>$this->_memberId]);
        if (!$instance) $this->error('该合约不存在');

        if ($this->_member['paypwd'] !== md5($this->request('password')))
            $this->error('密码有误');

        if ($instance['order_type']==1){
            $num = $instance['in_num'];
            $nums = $num;
        }else {

            if (($instance['period_day']-$instance['bonus_day'])==0)
            {
                $num = $instance['in_num'];
                $nums = $num;
            }else {

                $num_info =($instance['in_num'] *30)/100;
                $num      = $instance['in_num']-$num_info;
                $nums     = $instance['in_num'];
            }
        }

        try{
            $transaction = \Yii::$app->db->beginTransaction();
            StaticInstance::updateAll(['status'=>2],['id'=>$id]);
            ## 操作账本 增加
            $res1 = Balance::addBalance($this->_memberId, 1,$num, 15, $instance['id'],'',true);
            if(!$res1['state']) throw new \Exception($res1['msg']);
            ## 操作账本 减少
            $res = Balance::reduceBalance($this->_memberId, 3,$nums, 15, $instance['id']);
            if(!$res['state']) throw new \Exception($res['msg']);
            $transaction->commit();
            $this->out('提取成功');

        }catch (\Exception $e){
            $transaction->rollback();
            $this->error($e->getMessage());
        }
    }


}